<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Models\AgentModel;
use App\Models\airline\base\RouteModel;
use App\Models\finance\PayableTakeOrderModel;
use App\Models\finance\ReceivableGenericModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use App\Models\airline\base\FlightModel as BaseFlightModel;
use App\Models\OrderModel;
use App\Models\PayBillIdsModel;
use App\Models\RecBillIdsModel;
use App\Models\TakeOrderPayModel;
use App\Models\TakeOrderRecModel;
use Illuminate\Support\Facades\DB;

//数据统计
class Data extends Controller
{

    //数据统计
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);

        $query = TakeOrderModel::query();

        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->with('customer')
            ->where('flight_id', '>' , 0)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function ($item) {
//            $des_country = $item->flight->arrive_port_code ?? '';
            $split_order_count = 0;
            foreach($item->orders as $order) {
                $split_order_count += $order->split_order_addr->count();
            }

//            $recs = TakeOrderRecModel::select('symbol', DB::raw('sum(amount) as amount'))
//                ->where('take_order_id', $item->id)
//                ->groupBy('symbol')
//                ->get()->toArray();

            $recs = ReceivableGenericModel::with('detail')->where('take_order_id', $item->id)->first();

            $rec_total = $rec_total2 = 0;
            if($recs){
                $rec_total = $recs->detail?->sum('amount') ?? 0;
                $rec_total2 = $recs->status == 3 ? $rec_total : 0;
            }



//            $pays = TakeOrderPayModel::select('symbol', DB::raw('sum(amount) as amount'))
//                ->where('take_order_id', $item->id)
//                ->groupBy('symbol')
//                ->get();

            $pays = PayableTakeOrderModel::where('take_order_id', $item->id)->first();

            $pay_total = $pay_total2 = 0;
            if($pays){
                $pay_total = $pays->amount ?? 0;
            }

            $airline_flight_id = $item->flight?->items? $item->flight->items->pluck('airline_flight_id')->toArray() : [];

            $flight_no = BaseFlightModel::whereIn('id', $airline_flight_id)
                ->pluck('flight_number')->toArray();

            $routes = RouteModel::whereIn('id', $item->flight?->items->pluck('route_id') ??  [])
                ->pluck('name')->toArray();

            return [
                'id' => $item->id,
                'customer_name' => $item->customer->name ?? '',
                'customer_sn' => $item->customer->sn ?? '',
                'des_country' => $item->destination,
                'sn' => $item->sn,
                'status' => TakeOrderModel::STATUS_MAPS[$item->status],
                'slipt_order_count' => $split_order_count,
                'order_count' => $item->orders ? $item->orders->count() : 0,
                'reality_weight' => $item->reality_weight,
                'reality_weight2' => $item->reality_weight,
                'rec_count' => $rec_total,
                'pay_count' => $pay_total,
                'actual_rec' => $rec_total2,
                'actual_pay' => $pay_total2,
                'wait_rec' => '',
                'wait_pay' => '',
                'routes' => implode(',', $routes),
                'flight_no' => implode(',', $flight_no),
                'take_off_time' => $item->flight->take_off_time ?? '',
                'created_at' => $item->created_at->toDateTimeString(),
            ];
        });

        $total_rec = $total_pay = $order_count = 0;
        foreach ($list as $item){
           $total_rec += $item['rec_count'];
           $total_pay += $item['pay_count'];
           $order_count += $item['order_count'];
        }


        return $this->success([
            'list' => $list,
            'total' => $items->count(),
            'collect' => [
                'take_order' => $items->count(),
                'order' => $order_count,
                'rec' => $total_rec,
                'pay' => $total_pay,
            ]
        ]);
    }

    //应付数据统计
    public function pay(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);

        $query = PayBillIdsModel::query();

        $items = $query
        ->offset(($page-1) * $limit)
        ->limit($limit)
        ->with([
            'take_order' => function($query) {
                $query->with([
                    'flight',
                    'orders' => function($query) {
                        $query->withCount('split_order_addr');
                    }
                ])->withCount('orders');
            }
        ])->get();

        $list = $items->map(function($item) {
            $des_country = $item->take_order?->flight->items->first()->destination->name ?? '';
            $split_order_count = $item->take_order?->orders->sum('split_order_addr_count') ?? 0;
            
            $pays = TakeOrderPayModel::select('symbol', DB::raw('sum(amount) as amount'))
                ->where('take_order_id', $item->take_order_id)
                ->groupBy('symbol')
                ->get();

            $pay = [];
            foreach($pays as $pay_item) {
                $pay[] = $pay_item['symbol'] . $pay_item['amount'];
            }

            $routes = RouteModel::whereIn('id', $item->take_order?->flight->items->pluck('route_id') ?? [])
                ->pluck('name')
                ->toArray();


            $flight_no = BaseFlightModel::whereIn('id', $item->take_order?->flight->items->pluck('airline_flight_id') ?? [])
                ->pluck('flight_number')->toArray();

            return [
                'id' => $item->take_order_id,
                'agent_name' => $item->pay_bill->agent->name ?? '',
                'agent_type' => AgentModel::TYPE_LIST[$item->pay_bill->agent->type ?? ''] ?? '',
                'des_country' => $des_country,
                'take_order_sn' => $item->take_order->sn ?? '',
                'status' => TakeOrderModel::STATUS_MAPS[$item->take_order->status ?? ''] ?? '',
                'split_order_count' => $split_order_count,
                'order_count' => $item->take_order?->orders_count ?? '',
                'reality_weight' => $item->reality_weight2,
                'sum_pay' => implode(',', $pay),
                'actual_pay' => '',
                'wait_pay' => '',
                'routes' => implode(',', $routes),
                'flight_no' => implode(',', $flight_no),
                'take_off_time' => $item->take_order->flight->take_off_time ?? '',
                'created_at' => $item->take_order?->created_at->toDateTimeString() ?? '',
                'settle_time' => $item->take_order?->settle_time2 ?? ''
            ];
        });

        $take_order_count = PayBillIdsModel::query()->count(DB::raw('distinct take_order_id'));

        $order_count = OrderModel::whereIn('take_order_id', function($query) {
            $query->select('take_order_id')->from((new PayBillIdsModel())->getTable());
        })->count();

        $pays = TakeOrderPayModel::select('symbol', DB::raw('sum(amount) as amount'))
            ->groupBy('symbol')
            ->get();

        $pay = [];
        foreach($pays as $pay_item) {
            $pay[] = $pay_item['symbol'] . $pay_item['amount'];
        }

        return $this->success([
            'list' => $list,
            'total' => $query->count(),
            'collect' => [
                'take_order' => $take_order_count,
                'order' => $order_count,
                'pay' => implode(',', $pay),
                'actual_pay' => '',
                'wait_pay' => ''
            ]
        ]);
    }

    //应收数据统计
    public function rec(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);

        $query = RecBillIdsModel::query();

        $items = $query
        ->offset(($page-1) * $limit)
        ->limit($limit)
        ->with([
            'take_order' => function($query) {
                $query->with([
                    'flight',
                    'orders' => function($query) {
                        $query->withCount('split_order_addr');
                    }
                ])->withCount('orders');
            }
        ])
        ->paginate($limit, ['*'], 'page', $page);

        $list = $items->map(function($item) {
            $des_country = $item->take_order?->flight->items->first()->destination->name ?? '';
            $split_order_count = $item->take_order?->orders->sum('split_order_addr_count') ?? 0;
            
            $recs = TakeOrderRecModel::select('symbol', DB::raw('sum(amount) as amount'))
                ->where('take_order_id', $item->take_order_id)
                ->groupBy('symbol')
                ->get();

            $rec = [];
            foreach($recs as $rec_item) {
                $rec[] = $rec_item['symbol'] . $rec_item['amount'];
            }

            $routes = RouteModel::whereIn('id', $item->take_order?->flight->items->pluck('route_id') ?? [])
                ->pluck('name')
                ->toArray();


            $flight_no = BaseFlightModel::whereIn('id', $item->take_order?->flight->items->pluck('airline_flight_id') ?? [])
                ->pluck('flight_number')->toArray();

            return [
                'id' => $item->take_order_id,
                'customer_name' => $item->take_order?->customer->name ?? '',
                'customer_sn' => $item->take_order?->customer->sn ?? '',
                'des_country' => $des_country,
                'take_order_sn' => $item->take_order->sn ?? '',
                'status' => TakeOrderModel::STATUS_MAPS[$item->take_order->status ?? ''] ?? '',
                'split_order_count' => $split_order_count,
                'order_count' => $item->take_order?->orders_count ?? '',
                'reality_weight' => $item->reality_weight,
                'sum_rec' => implode(',', $rec),
                'actual_rec' => '',
                'wait_pay' => '',
                'routes' => implode(',', $routes),
                'flight_no' => implode(',', $flight_no),
                'take_off_time' => $item->take_order->flight->take_off_time ?? '',
                'created_at' => $item->take_order?->created_at->toDateTimeString() ?? '',
                'settle_time' => $item->take_order?->settle_time ?? ''
            ];
        });

        $take_order_count = PayBillIdsModel::query()->count(DB::raw('distinct take_order_id'));

        $order_count = OrderModel::whereIn('take_order_id', function($query) {
            $query->select('take_order_id')->from((new PayBillIdsModel())->getTable());
        })->count();

        $recs = TakeOrderPayModel::select('symbol', DB::raw('sum(amount) as amount'))
            ->groupBy('symbol')
            ->get();

        $rec = [];
        foreach($recs as $rec_item) {
            $rec[] = $rec_item['symbol'] . $rec_item['amount'];
        }

        return $this->success([
            'list' => $list,
            'total' => $items->total(),
            'collect' => [
                'take_order' => $take_order_count,
                'order' => $order_count,
                'rec' => implode(',', $rec),
                'actual_rec' => '',
                'wait_rec' => ''
             ]
        ]);
    }


}
